package com.core.image.tcp;

import com.core.image.core.Connector;
import com.core.image.core.IoContext;
import com.core.image.core.impl.IdleTimeoutScheduleJob;
import com.core.image.core.impl.IoSelectorProvider;
import com.core.image.core.impl.ScheduleJob;
import com.core.image.core.impl.SchedulerImpl;
import com.core.image.handler.ConnectorCloseChain;
import com.core.image.handler.ConnectorHandlerChain;
import com.core.image.utils.CloseUtils;
import com.core.image.utils.Foo;

import java.io.*;
import java.util.concurrent.TimeUnit;

/**
 * describe:
 *
 * @author 库琦
 * @date 2020/01/21
 */
public class Client {
    public static void main(String[] args) throws Exception{
        File file = Foo.getCacheDir("client");
        ServerInfo serverInfo = UDPSearcher.searchServer(1000);
        IoContext.setup()
                .ioProvider(new IoSelectorProvider())
                .scheduler(new SchedulerImpl(1))
                .start();
        TCPClient tcpClient = TCPClient.linkWith(serverInfo,file);
        if (tcpClient == null){
            return;
        }
      tcpClient.getCloseChain().appendLast(new ConnectorCloseChain() {
          @Override
          public boolean consume(ConnectorHandler clientHandler, Connector connector) {
              CloseUtils.close(System.in);
              return true;
          }
      });
        ScheduleJob scheduleJob = new IdleTimeoutScheduleJob(10, TimeUnit.SECONDS, tcpClient);
        tcpClient.schedule(scheduleJob);
        write(tcpClient);
    }

    public static  void write(TCPClient tcpClient){
        InputStream in = System.in;
        BufferedReader buffer = new BufferedReader(new InputStreamReader(in));
        try {
            do {
                String line = buffer.readLine();
                tcpClient.send(line);
            }while (true);

        }catch (Exception e){
            e.printStackTrace();
        }



    }
}
